package com.stone.activemqcase.config;/*

 */

import lombok.SneakyThrows;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * 主题消费者
 * @ClassName Consumer_topic
 * @Author Final
 * @Project DataStructures
 */
public class Consumer_topic {

    public static final String ACTIVEMQ_URL="tcp://127.0.0.1:61616";
    public static final String TOPIC_NAME="topic-stone";

    public static void main(String[] args) throws JMSException, IOException {
        //1、创建连接工厂
        ActiveMQConnectionFactory factory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);

        //2、通过连接工厂获得连接connection并访问
        Connection connection = factory.createConnection();
//        connection.start();

        connection.setClientID("Z3"); //订阅人
        //3、创建会话session
        //第一个参数叫事物第二个叫签收
        Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);

        //4、创建目的地(具体是主题或者队列)Destination destination可以是主题或者队列
        Topic topic = session.createTopic(TOPIC_NAME);

        TopicSubscriber durableSubscriber = session.createDurableSubscriber(topic, "..."); //创建持久化的订阅

//        //5、创建消费者
//        MessageConsumer consumer = session.createConsumer(topic);
//
//        consumer.setMessageListener(new MessageListener() {
//            @SneakyThrows
//            @Override
//            public void onMessage(Message message) {
//                if (message!=null && message instanceof TextMessage){
//                    TextMessage message1 = (TextMessage) message;
//                    System.out.println("消费者接受消息--------------------->"+message1.getText());
//                }
//            }
//        });
//        System.in.read();  //保证控制台不停止
        //6、资源关闭
//        consumer.close();

        connection.start();
        Message receive = durableSubscriber.receive();
        while (null!=receive){
            TextMessage receive1 = (TextMessage) receive;
            System.out.println(receive1.getText());

            receive = durableSubscriber.receive(); //不带参就
        }

        session.close();;
        connection.close();
    }
}
